package com.suitbim.commandserver.commandserver.util;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.entity.StringEntity;
import org.apache.http.message.BasicNameValuePair;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.net.URI;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class BimApiUtil {

    @Autowired
    private HttpClientUtil httpClientUtil;

    @Autowired
    private Gson gson;

    @Value("${bimrun-cas-server-rest-login-url}")
    private String casServerUrl;

    @Value("${bimrun-liferay-server-rest-login-url}")
    private String bimrunLoginUrl;

    @Value("${bimrun-liferay-api-login}")
    private String bimrunApiLoginUrl;

    @Value("${bimrun-liferay-api-get-group-id}")
    private String getGroupIdUrl;

    @Value("${bimrun-liferay-api-get-scene-info}")
    private String getSceneInfoUrl;

    @Value("${bimrun-create-scene-api}")
    private String createSceneUrl;

    //调用接口的频率应该不高，就不缓存session了，缓存即意味着管理

    private String casLogin(String username, String password) throws Exception {
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("username", username));
        params.add(new BasicNameValuePair("password", password));
        UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(params, "utf-8");
        HttpClientUtil.RequestBuilder requestBuilder = httpClientUtil.buildRequest().buildPost(new URI(casServerUrl))
                .setEntity(formEntity);
        requestBuilder.getResponse();
        String location = requestBuilder.getHeader("Location");
        String[] split = location.split("/");
        String tgt = split[split.length - 1].replace("\"", "");


        List<NameValuePair> stParams = new ArrayList<NameValuePair>();
        stParams.add(new BasicNameValuePair("service", bimrunLoginUrl));
        UrlEncodedFormEntity stFormEntity = new UrlEncodedFormEntity(stParams, "utf-8");
        HttpClientUtil.RequestBuilder requestBuilder1 = httpClientUtil.buildRequest().buildPost(new URI(casServerUrl + "/" + tgt)).setEntity(stFormEntity);
        requestBuilder1.getResponse();
        String st = requestBuilder1.getString();

        HttpClientUtil.RequestBuilder requestBuilder2 = httpClientUtil.buildRequest().buildPost(new URI(bimrunLoginUrl + "?ticket=" + st));
        HttpResponse response = requestBuilder2.getResponse();
        Header[] headers = response.getHeaders("Set-Cookie");

//        HttpClientUtil.RequestBuilder requestBuilder3 = httpClientUtil.buildRequest()
//                .buildGet(new URI("http://bim.suitbim.com.cn/api/jsonws/entities-portlet.interface/get-scenes/project-id/160756142/-search-word/max/10/offset/0"));
        String cookie = "";
        for (int i = 0; i < headers.length; i++) {
            Header header = headers[i];
            cookie += header.getValue();
        }

        return cookie;
    }

    public String jwtLogin(String username, String password) throws Exception {
        HashMap data = new HashMap();
        data.put("password", password);
        data.put("username", username);
        StringEntity stringEntity = new StringEntity(gson.toJson(data));
        stringEntity.setContentType("application/json");

        HttpClientUtil.RequestBuilder requestBuilder = httpClientUtil.buildRequest().buildPost(new URI(bimrunApiLoginUrl)).setEntity(stringEntity);
        HttpResponse response = requestBuilder.getResponse();
        String json = requestBuilder.getString();
        Map map = gson.fromJson(json, Map.class);
        String token = (String) map.get("token");
        return token;
    }

    public Integer getSceneVersion(Long sceneId) throws Exception {
        HttpClientUtil.RequestBuilder requestBuilder = httpClientUtil.buildRequest().buildGet(new URI(getSceneInfoUrl + sceneId));
        HttpResponse response = requestBuilder.getResponse();
        String json = requestBuilder.getString();
        Map map = gson.fromJson(json, Map.class);
        return Integer.valueOf(String.valueOf(map.get("version")));
    }

    public String getGroupId(Long projectId) throws Exception {
        HttpClientUtil.RequestBuilder requestBuilder = httpClientUtil.buildRequest().buildGet(new URI(getGroupIdUrl + projectId));
        HttpResponse response = requestBuilder.getResponse();
        String json = requestBuilder.getString();
        return json;
    }

    public Long createScene(String username, String password, String projectId, String sceneName) throws Exception {
        String token = jwtLogin(username, password);
        String groupId = getGroupId(Long.valueOf(projectId));
//        HashMap data = new HashMap();
//        data.put("groupId", Long.valueOf(groupId));
//        data.put("projectId", Long.valueOf(projectId));
//        data.put("name", sceneName);
//        StringEntity stringEntity = new StringEntity(gson.toJson(data));
//        stringEntity.setContentType("application/json");

        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("groupId", groupId));
        params.add(new BasicNameValuePair("projectId", projectId));
        params.add(new BasicNameValuePair("name", sceneName));
        UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(params, "utf-8");

//        HttpEntity formEntity = MultipartEntityBuilder.create()
//                .addTextBody("groupId", groupId)
//                .addTextBody("projectId", projectId)
//                .addTextBody("name", sceneName)
//                .setContentType(ContentType.MULTIPART_FORM_DATA)
//                .build();

        HttpClientUtil.RequestBuilder requestBuilder = httpClientUtil.buildRequest().buildPost(new URI(createSceneUrl))
                .setEntity(formEntity)
                .addHeader("Cookie", "Bearer=" + token);
        HttpResponse response = requestBuilder.getResponse();
        String json = requestBuilder.getString();
        Map map = gson.fromJson(json, new TypeToken<Map<String, Long>>() {
        }.getType());
        Long id = (Long) map.get("id");
        return id;
    }

//    public Long createSceneUrl(String username, String password, String projectId, String sceneName) {
//        try {
//            String cookie = casLogin(username, password);
//
//            Map data = new HashMap();
//            data.put("projectId", projectId);
//            data.put("name", sceneName);
//            List<NameValuePair> params = new ArrayList<NameValuePair>();
//            params.add(new BasicNameValuePair("data", gson.toJson(data)));
//            params.add(new BasicNameValuePair("file", null));
//            UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(params, "utf-8");
//            HttpClientUtil.RequestBuilder requestBuilder = httpClientUtil.buildRequest().buildPost(new URI("http://bim.suitbim.com.cn/api/jsonws/entities-portlet.interface/save-scene"))
//                    .setEntity(formEntity);
//            requestBuilder.addHeader("Cookie", cookie);
//            requestBuilder.getResponse();
//            String json = requestBuilder.getString();
//            Map map = gson.fromJson(json, Map.class);
//            Map msg = (Map) map.get("msg");
//            Map error_message = (Map) map.get("error_message");
//            System.out.println(error_message);
//
//            Double id = (Double) msg.get("id");
//            return id.longValue();
//        } catch (IOException e) {
//            e.printStackTrace();
//        } catch (URISyntaxException e) {
//            e.printStackTrace();
//        }
//
//        return 0L;
//    }
}
